package com.gravata.enigma.reader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.content.Context;

import com.gravata.enigma.activities.TelaInicial;

public class ReloaderUtil {


    public static boolean reload(Context context) throws IOException{
		URL url = new URL(TelaInicial.profile.getUrlCompleta()+"/web/servicelistreload?mode=2");
        URLConnection con = url.openConnection();
        System.out.println("Connection is : " + con);

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                con.getInputStream()));

        String inputLine;
        String fullStr = "";
        while ((inputLine = reader.readLine()) != null)
            fullStr = fullStr.concat(inputLine + "\n");

        InputStream istream = url.openStream();
        boolean result = false;
        try{
            DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder();

            Document doc = builder.parse(istream);

            doc.getDocumentElement().normalize();


        	NodeList nList = doc.getElementsByTagName("e2state");


        	for (int temp = 0; temp < nList.getLength(); temp++) {

        		Node nNode = nList.item(temp);

        		System.out.println("\nCurrent Element :" + nNode.getNodeName());

        		if (nNode.getNodeType() == Node.ELEMENT_NODE) {

        			Element eElement = (Element) nNode;
        			result=Boolean.parseBoolean(eElement.getTextContent().toLowerCase());

        		}
        	}
           }catch(Exception e){
        	   e.printStackTrace();
        }
        return result;
    }

    private static String getTagValue(String sTag, Element eElement) {
        NodeList nlList = eElement.getElementsByTagName(sTag).item(0)
                .getChildNodes();

        Node nValue = (Node) nlList.item(0);

        return nValue.getNodeValue();

    }

}